package org.example.novel.utlis;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }


    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    /**
     * 获取bean对象
     */
    public static <T> T getBean(Class<T> tClass)
    {
        return getApplicationContext().getBean(tClass);
    }

    /**
     * 根据名称字符串获取bean对象
     * @param name
     * @return
     * @param <T>
     */
    public static <T> T getBean(String name)
    {
        return (T) getApplicationContext().getBean(name);
    }

}
